# coding:utf-8


from flask import render_template, redirect

from . import main
from .forms import MaterialForm, UploadForm
from .. import db
from .models import Material
from ..helpers import batch_insert_data


@main.route('/add', methods=['GET', 'POST'])
def add():
    form = MaterialForm()
    material = Material()
    if form.validate_on_submit():
        material.name = form.name.data
        material.keywords = form.keywords._value()
        material.location = form.location.data
        if form.picture.data:
            form.picture._save_file(form.picture.data, form.picture.data.filename)
            material.picture = form.picture.data.filename
        material.storage_time = form.storage_time.data
        material.description = form.description.data
        material.expiration = form.expiration.data
        db.session.add(material)
        return redirect('material')  # 见admin/__init__.py
    # print form.errors
    return render_template('add.html',
                           form=form
                           )


@main.route('/batch_add', methods=['GET', 'POST'])
def batch_add():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.batch_file.data
        batch_insert_data(f)
        return redirect('material')
    return render_template('batch_add.html', form=form)


